package com.beiing.tianshuai.tianshuai.adapter;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.entity.HomeBean;
import com.beiing.tianshuai.tianshuai.entity.IndexListBean;
import com.beiing.tianshuai.tianshuai.util.DateUtil;
import com.beiing.tianshuai.tianshuai.util.DisplayUtil;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.beiing.tianshuai.tianshuai.widget.RadiusBackgroundSpan;
import com.beiing.tianshuai.tianshuai.widget.RoundAngleImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

import java.nio.channels.NonReadableChannelException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 首页列表数据适配器
 *
 * @author Jinda Yang
 * @date 2017/11/17
 */

public class HomeRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_ACTIVE = 0;
    private static final int TYPE_FRESH_ONE = 1;
    private static final int TYPE_FRESH_THREE = 2;

    private final RequestOptions freshRequestOptions;
    private final RadiusBackgroundSpan radiusBackgroundSpan;

    private Context mContext;
    private List<IndexListBean> mList;

    private OnItemClickListener mOnItemClickListener;

    public HomeRecyclerViewAdapter(Context mContext, List<IndexListBean> indexListBeans) {
        this.mContext = mContext;
        this.mList = indexListBeans;

        //新鲜事图片加载的options
        freshRequestOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .override(300, 168);

        //条目类型标签背景
        radiusBackgroundSpan = new RadiusBackgroundSpan(
                mContext,
                Color.parseColor("#6C6C6C"),
                Color.parseColor("#9B9B9B"),
                10
        );
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder;
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        switch (viewType) {
            case TYPE_ACTIVE:
                holder = new ActiveHolder(layoutInflater.inflate(R.layout.item_hot_active, parent, false));
                break;
            case TYPE_FRESH_ONE:
                holder = new OnePicFreshHolder(layoutInflater.inflate(R.layout.item_home_discovery_onepic, parent, false));
                break;
            case TYPE_FRESH_THREE:
                holder = new ThreePicFreshHolder(layoutInflater.inflate(R.layout.item_home_discovery_threepic, parent, false));
                break;
            default:
                holder = new ActiveHolder(layoutInflater.inflate(R.layout.item_hot_active, parent, false));
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
        IndexListBean bean = mList.get(position);
        if (holder instanceof ActiveHolder) {
            ((ActiveHolder) holder).setData(bean);
            ((ActiveHolder) holder).setListener(bean);
        } else if (holder instanceof OnePicFreshHolder) {
            ((OnePicFreshHolder) holder).setData(bean);
            ((OnePicFreshHolder) holder).setListener(bean);
        } else if (holder instanceof ThreePicFreshHolder) {
            ((ThreePicFreshHolder) holder).setData(bean);
            ((ThreePicFreshHolder) holder).setListener(bean);
        }
    }

    @Override
    public int getItemViewType(int position) {
        int result;
        IndexListBean indexListBean = mList.get(position);
        String type = indexListBean.getType();
        switch (type) {
            case "active":
                result = TYPE_ACTIVE;
                break;
            case "fresh":
                String covers = indexListBean.getCover();
                String[] split = covers.split(",");
                //新鲜事封面图的最大数量
                int maxCoverSize = 3;
                if (split.length >= maxCoverSize) {
                    result = TYPE_FRESH_THREE;
                } else {
                    result = TYPE_FRESH_ONE;
                }
                break;
            default:
                result = TYPE_ACTIVE;
        }
        return result;
    }

    @Override
    public int getItemCount() {
        return mList.isEmpty() ? 0 : mList.size();
    }

    class ActiveHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.active_title)
        TextView activeTitle;
        @BindView(R.id.civ_avatar)
        CircleImageView civAvatar;
        @BindView(R.id.tv_sponsor)
        TextView tvSponsor;
        @BindView(R.id.tv_watch_times)
        TextView tvWatchTimes;
        @BindView(R.id.tv_active_time)
        TextView tvActiveTime;
        @BindView(R.id.iv_active_cover)
        ImageView ivActiveCover;

        private ActiveHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void setData(IndexListBean bean) {

            //设置活动标题
            SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
            stringBuilder.append("活动");
            stringBuilder.append("  ");
            stringBuilder.append(bean.getTitle());
            stringBuilder.setSpan(
                    radiusBackgroundSpan,
                    0,
                    2,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            );
            activeTitle.setText(stringBuilder);

            //设置活动封面图
            Glide.with(mContext)
                    .load(HttpRequestConstant.ACTIVITY_PIC_HEAD + bean.getCover())
                    .apply(freshRequestOptions)
                    .into(ivActiveCover);

            //设置用户头像
            Glide.with(mContext)
                    .load(HttpRequestConstant.USER_PIC_HEAD + bean.getUserAvatar())
                    .into(civAvatar);

            //设置用户昵称
            tvSponsor.setText(bean.getUserName());

            //设置浏览次数
            tvWatchTimes.setText(bean.getViewCount());

            //设置活动状态
            String actionTime = bean.getActionTime();
            String exitTime = bean.getExitTime();
            if (TextUtils.isEmpty(actionTime) && TextUtils.isEmpty(exitTime)) {
                tvActiveTime.setText("未知");
            } else {
                tvActiveTime.setText(DateUtil.getActiveTime(actionTime, exitTime));
            }
        }

        public void setListener(final IndexListBean bean) {

            //头像点击事件
            civAvatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onAuthorClick(v, getAdapterPosition(), bean);
                    }
                }
            });

            //昵称点击事件
            tvSponsor.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onAuthorClick(v, getAdapterPosition(), bean);
                    }
                }
            });

            //条目点击事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onActiveClick(view, getAdapterPosition(), bean);
                    }
                }
            });
        }
    }

    class OnePicFreshHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.discovery_title)
        TextView discoveryTitle;
        @BindView(R.id.civ_avatar)
        CircleImageView civAvatar;
        @BindView(R.id.tv_publisher)
        TextView tvPublisher;
        @BindView(R.id.tv_watch_times)
        TextView tvWatchTimes;
        @BindView(R.id.tv_publish_time)
        TextView tvPublishTime;
        @BindView(R.id.iv_discovery_cover)
        RoundAngleImageView ivDiscoveryCover;

        private OnePicFreshHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void setData(IndexListBean bean) {

            //设置标题
            SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
            stringBuilder.append("发现");
            stringBuilder.append("  ");
            stringBuilder.append(bean.getTitle());
            stringBuilder.setSpan(
                    radiusBackgroundSpan,
                    0,
                    2,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            );
            discoveryTitle.setText(stringBuilder);

            //设置封面
            String cover = bean.getCover();
            String regex = ",";
            if (cover.contains(regex)) {
                String[] split = cover.split(regex);
                cover = split[0];
            }
            Glide.with(mContext).load(HttpRequestConstant.FRESH_COVER_URL + cover)
                    .apply(freshRequestOptions)
                    .into(ivDiscoveryCover);

            //设置用户头像
            Glide.with(mContext).load(HttpRequestConstant.USER_PIC_HEAD + bean.getUserAvatar())
                    .into(civAvatar);

            //设置用户昵称
            tvPublisher.setText(bean.getUserName());

            //设置浏览次数
            tvWatchTimes.setText(bean.getViewCount());

            //设置发布时间
            tvPublishTime.setText(DateUtil.timeStamp2Date(bean.getTime(), "yyyy-MM-dd"));
        }

        public void setListener(final IndexListBean bean) {

            //用户头像点击事件
            civAvatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onAuthorClick(v, getAdapterPosition(), bean);
                    }
                }
            });

            //用户昵称点击事件
            tvPublisher.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onAuthorClick(v, getAdapterPosition(), bean);
                    }
                }
            });

            //条目点击事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onFreshClick(view, getAdapterPosition(), bean);
                    }
                }
            });
        }
    }

    class ThreePicFreshHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.discovery_title)
        TextView discoveryTitle;
        @BindView(R.id.discovery_cover1)
        RoundAngleImageView discoveryCover1;
        @BindView(R.id.discovery_cover2)
        RoundAngleImageView discoveryCover2;
        @BindView(R.id.discovery_cover3)
        RoundAngleImageView discoveryCover3;
        @BindView(R.id.civ_avatar)
        CircleImageView civAvatar;
        @BindView(R.id.tv_publisher)
        TextView tvPublisher;
        @BindView(R.id.tv_watch_times)
        TextView tvWatchTimes;
        @BindView(R.id.tv_publish_time)
        TextView tvPublishTime;

        private ThreePicFreshHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void setData(IndexListBean bean) {

            //设置标题
            SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
            stringBuilder.append("发现");
            stringBuilder.append("  ");
            stringBuilder.append(bean.getTitle());
            stringBuilder.setSpan(
                    radiusBackgroundSpan,
                    0,
                    2,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            );
            discoveryTitle.setText(stringBuilder);

            //设置用户头像
            Glide.with(mContext).load(HttpRequestConstant.USER_PIC_HEAD + bean.getUserAvatar())
                    .into(civAvatar);

            //设置用户昵称
            tvPublisher.setText(bean.getUserName());

            //设置浏览次数
            tvWatchTimes.setText(bean.getViewCount());

            //设置发布时间
            tvPublishTime.setText(DateUtil.timeStamp2Date(bean.getTime(), "yyyy-MM-dd"));

            //设置封面图
            String cover = bean.getCover();
            String[] coversAll = cover.split(",");
            //屏幕宽度像素
            float screenWidth = DisplayUtil.getMobileWidth(mContext);
            ViewGroup.LayoutParams layoutParams = discoveryCover1.getLayoutParams();
            layoutParams.width = (int) ((screenWidth - DisplayUtil.dip2px(mContext, 30)) / 3);
            layoutParams.height = (int) (layoutParams.width / 1.78);
            discoveryCover1.setLayoutParams(layoutParams);
            ViewGroup.LayoutParams layoutParams1 = discoveryCover2.getLayoutParams();
            layoutParams1.width = (int) ((screenWidth - DisplayUtil.dip2px(mContext, 30)) / 3);
            layoutParams1.height = (int) (layoutParams.width / 1.78);
            discoveryCover2.setLayoutParams(layoutParams1);
            ViewGroup.LayoutParams layoutParams2 = discoveryCover3.getLayoutParams();
            layoutParams2.width = (int) ((screenWidth - DisplayUtil.dip2px(mContext, 30)) / 3);
            layoutParams2.height = (int) (layoutParams.width / 1.78);
            discoveryCover3.setLayoutParams(layoutParams2);
            Glide.with(mContext).load(HttpRequestConstant.FRESH_COVER_URL + coversAll[0])
                    .apply(freshRequestOptions)
                    .into(discoveryCover1);
            Glide.with(mContext).load(HttpRequestConstant.FRESH_COVER_URL + coversAll[1])
                    .apply(freshRequestOptions)
                    .into(discoveryCover2);
            Glide.with(mContext).load(HttpRequestConstant.FRESH_COVER_URL + coversAll[2])
                    .apply(freshRequestOptions)
                    .into(discoveryCover3);
        }

        public void setListener(final IndexListBean bean) {

            //用户头像点击事件
            civAvatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onAuthorClick(v, getAdapterPosition(), bean);
                    }
                }
            });

            //用户昵称点击事件
            tvPublisher.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onAuthorClick(v, getAdapterPosition(), bean);
                    }
                }
            });

            //条目点击事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onFreshClick(view, getAdapterPosition(), bean);
                    }
                }
            });
        }
    }

    public interface OnItemClickListener {

        /**
         * 活动条目点击事件
         *
         * @param view     点击的视图
         * @param position 点击条目所在位置
         * @param bean     点击条目包含的数据内容
         */
        void onActiveClick(View view, int position, IndexListBean bean);

        /**
         * 新鲜事条目点击事件
         *
         * @param view     点击的视图
         * @param position 点击条目所在位置
         * @param bean     点击条目包含的数据内容
         */
        void onFreshClick(View view, int position, IndexListBean bean);

        /**
         * 作者头像和昵称的点击事件
         *
         * @param view     点击的视图
         * @param position 点击条目所在位置
         * @param bean     点击条目包含的数据内容
         */
        void onAuthorClick(View view, int position, IndexListBean bean);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }
}
